const http = require('http')
const path = require('path')
const fs = require('fs')
const mimeTypes = require('mime-types')

const server =http.createServer((req,res)=>{
    let filePath=path.resolve(__dirname,path.join('www',req.url))
    if(fs.existsSync(filePath)){//判断路径是否有对应的文件
        const status =fs.statSync(filePath)
        const isDir=status.isDirectory()
        if(isDir){
            filePath=path.join(filePath,'index.html')
        }
        //读取文件资源
        const content =fs.readFileSync(filePath)
        const {ext} =path.parse(filePath)
        // if(ext ==='.png'){
        //     res.writeHead(200,{'Content-Type':'image/png'})
        // }else{
        //     res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'})
        // }0
        res.writeHead(200,{'Content-Type':mimeTypes.lookup(ext)})
        res.end(content)
    }else{
        res.writeHead(404,{'Content-Type':'text/html'})
        res.end('<h1>404 NOT FOUND</h1>')
    }
})

server.listen(8080,()=>{
  console.log('server is running at http://127.0.0.1:8080')
})